package com.czl.module_storehouse.activity.remand.selected;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.czl.base.data.bean.tengyun.RecordRemandBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.module_base.activity.BaseRecyclerViewActivity;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.utils.ParcelHelper;
import com.czl.module_service.event.DamageRegisBackEvent;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.remand.damage.DamageRegisActivity;
import com.czl.module_storehouse.adapter.RemandSelectedOrderAdapter;
import com.czl.module_storehouse.databinding.FooterRemandSelectedOrderBinding;
import com.czl.module_storehouse.databinding.HeaderRemandSelectedOrderBinding;
import com.czl.module_storehouse.event.DamageRegisPostEvent;
import com.czl.module_storehouse.event.RecordRemandBeanEvent;
import com.czl.module_storehouse.event.RemandSelectedGoodsEvent;
import com.czl.module_storehouse.event.RemandSelectedOrderEvent;
import com.czl.module_storehouse.mvp.presenter.RemandHomePresenter;
import com.czl.module_storehouse.mvp.view.RemandHomeView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择采购单
 *
 * @author xubin
 */
public class RemandSelectedOrderActivity extends BaseRecyclerViewActivity<HeaderRemandSelectedOrderBinding> implements RemandHomeView {

    private SortBean mSortBean;
    private RemandSelectedOrderAdapter mAdapter;
    private int mSelectPosition;

    @InjectPresenter
    RemandHomePresenter mRemandHomePresenter;
    private FooterRemandSelectedOrderBinding mFooterBinding;

    @Override
    protected HeaderRemandSelectedOrderBinding getChildBinding(LayoutInflater layoutInflater, FrameLayout containerTop) {
        return HeaderRemandSelectedOrderBinding.inflate(layoutInflater, containerTop, true);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mFooterBinding = FooterRemandSelectedOrderBinding.inflate(getLayoutInflater(), binding.containerBottom, true);
        mToolBinding.toolbarContentTitle.setText("选择领用/借用单");
        mAdapter = new RemandSelectedOrderAdapter(R.layout.item_remand_select_order, new ArrayList<>());
        mChildBinding.layoutSearch.etSearch.setHint("输入领用/借用人搜索");
        initListener();
        binding.recyclerView.setAdapter(mAdapter);
        LiveEventBus.get(DamageRegisBackEvent.class).observe(this, event -> setDamageRegisSortBean(event.getSortBean()));

        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(RemandSelectedGoodsEvent event) {
        SortBean sortBean = event.getSortBean();
        if (sortBean == null) {
            return;
        }
        mSortBean = ParcelHelper.copy(sortBean);
        mAdapter.setMaxCount(event.getMaxNum());
        mChildBinding.tvName.setText(mSortBean.getSortName());
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(DamageRegisPostEvent event) {
        setDamageRegisSortBean(event.getSortBean());
    }

    private void setDamageRegisSortBean(SortBean sortBean) {
        if (sortBean == null) {
            return;
        }
        RecordRemandBean item = mAdapter.getItem(mSelectPosition);
        item.setExcNum(sortBean.getExcNum());
        item.setExcLossesNum(sortBean.getExcLossesNum());
        item.setExcLocatId(sortBean.getExcLocatId());
        item.setDamageComment(sortBean.getDamageComment());
        mAdapter.setData(mSelectPosition, item);
        setTextViewEnable();
    }

    @Override
    protected void loadData() {
        super.loadData();
        loadData(true, "");
    }

    @Override
    protected void loadMore() {
        super.loadMore();
        loadData(false, "");
    }

    protected void loadData(boolean refresh, String name) {
        if (mSortBean != null) {
            mRemandHomePresenter.getSortUseInfo(refresh, name, mSortBean.getSortId());
        }
    }

    protected void initListener() {
        mAdapter.setOnNumTextChangeListener(this::setTextViewEnable);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            mSelectPosition = position;
            if (R.id.tv_damage_num == view.getId()) {
                EventBus.getDefault().postSticky(new RemandSelectedOrderEvent(mSortBean, mAdapter.getItem(position)));
                startActivity(new Intent(getContext(), DamageRegisActivity.class));
            }
        });
        mChildBinding.layoutSearch.ivSearch.setOnClickListener(v -> search());
        mFooterBinding.textAdd.setOnClickListener(v -> submit());
    }

    private void submit() {
        RecordRemandBeanEvent event = new RecordRemandBeanEvent();
        event.setRecordRemandBeanList(mAdapter.getData());
        EventBus.getDefault().postSticky(event);
        finish();
    }

    private void search() {
        //搜索
        String userName = mChildBinding.layoutSearch.etSearch.getText().toString();
        loadData(true, userName);
    }

    private void setTextViewEnable() {
        List<RecordRemandBean> data = mAdapter.getData();
        int totalReturnNum = 0;
        int totalDamageNum = 0;
        for (RecordRemandBean bean : data) {
            totalReturnNum += bean.getReturnNumInt();
            totalDamageNum += bean.getExcNumInt();
        }
        mFooterBinding.tvSortCount.setText(getString(R.string.intact_num_placeholder, totalReturnNum));
        mFooterBinding.tvDamageCount.setText(getString(R.string.damage_risk_placeholder, totalDamageNum));
        if (totalDamageNum > 0) {
            mFooterBinding.tvDamageCount.setVisibility(View.VISIBLE);
        } else {
            mFooterBinding.tvDamageCount.setVisibility(View.GONE);
        }
        mFooterBinding.textAdd.setEnabled((totalReturnNum + totalDamageNum) > 0);
    }

    @Override
    public <T> void showData(T t) {
        super.showData(t);
        handleResponseData(mAdapter, mRemandHomePresenter.getPageNo(), (ListBean<RecordRemandBean>) t);
        if (((ListBean<?>) t).getList() == null || ((ListBean<RecordRemandBean>) t).getList().isEmpty()) {
            mFooterBinding.getRoot().setVisibility(View.GONE);
        } else {
            mFooterBinding.getRoot().setVisibility(View.VISIBLE);
        }
        if (mSortBean == null) {
            return;
        }
        List<RecordRemandBean> recordList = mSortBean.getRecordList();
        if (recordList == null || recordList.isEmpty()) {
            return;
        }
        List<RecordRemandBean> selectList = new ArrayList<>();
        List<RecordRemandBean> data = mAdapter.getData();
        for (int i = 0; i < data.size(); i++) {
            RecordRemandBean remandBean = data.get(i);
            if (remandBean.getUserId() == null || remandBean.getUserId().isEmpty()) {
                continue;
            }
            for (RecordRemandBean recordRemandBean : recordList) {
                if (remandBean.getUserId().equals(recordRemandBean.getUserId())) {
                    mAdapter.setData(i, recordRemandBean);
                    selectList.add(recordRemandBean);
                    break;
                }
            }
        }
        mAdapter.setSelectedList(selectList);
        setTextViewEnable();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mFooterBinding != null) {
            mFooterBinding.unbind();
        }
    }
}
